package team.southcat.wsyygh.hospital.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import team.southcat.wsyygh.common.client.AreaFeignClient;
import team.southcat.wsyygh.common.client.CategoryFeignClient;
import team.southcat.wsyygh.common.exception.WsyyghException;
import team.southcat.wsyygh.common.result.Result;
import team.southcat.wsyygh.common.util.MD5Util;
import team.southcat.wsyygh.model.pojo.common.Area;
import team.southcat.wsyygh.model.pojo.common.Category;
import team.southcat.wsyygh.model.pojo.hospital.*;
import team.southcat.wsyygh.hospital.mapper.HospitalMapper;
import team.southcat.wsyygh.hospital.service.HospitalService;
import team.southcat.wsyygh.model.pojo.user.Admin;
import team.southcat.wsyygh.user.client.AdminFeignClient;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author QiuSiYi
 * @since 2023-04-20
 */
@Service
public class HospitalServiceImpl extends ServiceImpl<HospitalMapper, Hospital> implements HospitalService {

    /**
     * 大小写字母
     */
    public final static String[] word = {
            "a", "b", "c", "d", "e", "f", "g",
            "h", "j", "k", "m", "n",
            "p", "q", "r", "s", "t",
            "u", "v", "w", "x", "y", "z",
            "A", "B", "C", "D", "E", "F", "G",
            "H", "J", "K", "M", "N",
            "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"
    };

    /**
     * 数字 1-9
     */
    public final static String[] num = {
            "1", "2", "3", "4", "5", "6", "7", "8", "9"
    };


    public static String randomPassword() {
        StringBuffer stringBuffer = new StringBuffer();
        Random random = new Random(new Date().getTime());
        boolean flag = false;
        //输出几位密码长度  这里是有可能8 ，9 ，10 位
        int length = random.nextInt(3) + 8;
        for (int i = 0; i < length; i++) {
            if (flag) {
                stringBuffer.append(num[random.nextInt(num.length)]);
            } else {
                stringBuffer.append(word[random.nextInt(word.length)]);
            }
            flag = !flag;
        }
        return stringBuffer.toString();
    }

    @Autowired
    private AreaFeignClient areaFeignClient;

    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Autowired
    private AdminFeignClient adminFeignClient;

    private long maxFileSize = 2097152; // 文件最大大小（单位：字节）
    // 允许上传的文件类型
    private static final String[] ALLOWED_FILE_TYPES = {"jpg", "png"};

    /**
     * 根据ID获取医院详情
     *
     * @param id
     * @return
     */
    @Override
    public HospitalVo selectById(Long id) {
        Hospital hospital = baseMapper.selectById(id);
        HospitalVo hospitalVO = switchVo(hospital);
        return hospitalVO;
    }

    public HospitalVo switchVo(Hospital hospital) {
        if (hospital == null){
            return null;
        }
        HospitalVo hospitalVO = new HospitalVo();
        //对象拷贝
        BeanUtils.copyProperties(hospital, hospitalVO);

        //使用Feign远程调用AreaController的getById方法，但是返回来的数据是Json数据需要转换
        if (hospital.getProvinceId() != null){
            Object provinceObject = areaFeignClient.getById(hospital.getProvinceId()).getData();
            Area province = JSONObject.parseObject(JSON.toJSONString(provinceObject), Area.class);
            hospitalVO.setProvince(province.getName());
        }
        if (hospital.getProvinceId() != null){
            Object cityObject = areaFeignClient.getById(hospital.getCityId()).getData();
            Area city = JSONObject.parseObject(JSON.toJSONString(cityObject), Area.class);
            hospitalVO.setCity(city.getName());

        }
        if (hospital.getProvinceId() != null){
            Object districtObject = areaFeignClient.getById(hospital.getDistrictId()).getData();
            Area district = JSONObject.parseObject(JSON.toJSONString(districtObject), Area.class);
            hospitalVO.setDistrict(district.getName());
        }


        //设置医院等级
        Object object = categoryFeignClient.getById(hospital.getHospitalType()).getData();
        Category category = JSONObject.parseObject(JSON.toJSONString(object), Category.class);
        hospitalVO.setHospitalTypeName(category.getName());
        return hospitalVO;
    }


    @Override
    public Page getHospitalPageList(int page, int limit, HospitalVo hospitalVo) {
        //分页构造器,传入页码和大小
        Page<Hospital> pageInfo = new Page<>(page, limit);
        //条件构造器
        LambdaQueryWrapper<Hospital> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(hospitalVo.getDistrict() != null, Hospital::getDistrictId,hospitalVo.getDistrictId());
        queryWrapper.eq(hospitalVo.getCityId() != null, Hospital::getCityId,hospitalVo.getCityId());
        queryWrapper.eq(hospitalVo.getProvinceId() != null, Hospital::getProvinceId,hospitalVo.getProvinceId());
        queryWrapper.eq(hospitalVo.getHospitalName() != null, Hospital::getHospitalName,hospitalVo.getHospitalName());
        queryWrapper.eq(hospitalVo.getHospitalType() != null, Hospital::getHospitalType, hospitalVo.getHospitalType());

        //执行查询
        Page<Hospital> hospitalPage = this.page(pageInfo, queryWrapper);

        //对象拷贝为Vo对象Page
        Page<HospitalVo> voPage = new Page<>();
        BeanUtils.copyProperties(hospitalPage, voPage);

        //取出数据并赋值转换
        List<Hospital> records = pageInfo.getRecords();
        //使用流转换,遍历将医生id改为医生名字
        List<HospitalVo> hospitalVos = records.stream().map((item) -> {
            HospitalVo hosVo = new HospitalVo();
            BeanUtils.copyProperties(item, hosVo);

            hosVo.setStatusname(item.getStatus() == 0 ? "未上线" : "已上线");

            String fulladdress = "";
            if(item.getProvinceId()!=null){
                Object provinceObject = areaFeignClient.getById(item.getProvinceId()).getData();
                Area province = JSONObject.parseObject(JSON.toJSONString(provinceObject), Area.class);
                hosVo.setProvince(province.getName());
                fulladdress += province.getName();
            }
            if(item.getCityId()!=null){
                Object cityObject = areaFeignClient.getById(item.getCityId()).getData();
                Area city = JSONObject.parseObject(JSON.toJSONString(cityObject), Area.class);
                hosVo.setCity(city.getName());
                fulladdress += city.getName();
            }
            if(item.getDistrictId()!=null){
                Object districtObject = areaFeignClient.getById(item.getDistrictId()).getData();
                Area district = JSONObject.parseObject(JSON.toJSONString(districtObject), Area.class);
                hosVo.setDistrict(district.getName());
                fulladdress += district.getName();
            }

            if(item.getAddress()!=null){
                fulladdress += item.getAddress();
            }

            //设置地址
            hosVo.setFulladdress(fulladdress);

            //设置医院等级
            Object object = categoryFeignClient.getById(item.getHospitalType()).getData();
            Category category = JSONObject.parseObject(JSON.toJSONString(object), Category.class);
            hosVo.setHospitalTypeName(category.getName());

            return hosVo;
        }).collect(Collectors.toList());

        //放数据，返回
        voPage.setRecords(hospitalVos);
        return voPage;
    }

    @Override
    @Transactional
    public Result addHospital(Hospital hospital) {

        if(hospital.getHospitalName() == null){
            return Result.fail().message("必须填写医院名称");
        }
        if(hospital.getContactsName() == null){
            return Result.fail().message("必须填写联系人名称");
        }
        if(hospital.getContactsPhone() == null){
            return Result.fail().message("必须填写联系人电话");
        }

        String phone = hospital.getContactsPhone();
        LambdaQueryWrapper<Hospital> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Hospital::getContactsPhone, phone);
        Hospital have = baseMapper.selectOne(queryWrapper);

        if (have != null){
            return Result.fail().message("该手机号已被使用于联系人，请更换");
        }

        hospital.setStatus(0);
        int insert = baseMapper.insert(hospital);
        Admin admin = new Admin();
        String password = randomPassword();
        admin.setHospitalId(hospital.getId());
        admin.setAdminName(hospital.getContactsPhone());
        admin.setPhone(hospital.getContactsPhone());
        admin.setRole("1");
        admin.setStatus("1");
        admin.setPassword(MD5Util.encrypt(password));
        Result result = adminFeignClient.addAdmin(admin);
        return insert == 1 ? Result.ok(password) : Result.fail().message("保存失败！");
    }

    @Override
    public HospitalVo getByAdminId(String adminId) {
        int id = Integer.valueOf(adminId);
        Object adminObj = adminFeignClient.getAdminById(id).getData();
        Admin admin = JSONObject.parseObject(JSON.toJSONString(adminObj), Admin.class);
        Long hospitalId = admin.getHospitalId();
        Hospital hospital = baseMapper.selectById(hospitalId);
        HospitalVo hospitalVo = this.switchVo(hospital);
        return hospitalVo;
    }

    @Override
    public List<Hospital> getByHospitalName(String hosname) {
        LambdaQueryWrapper<Hospital> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Hospital::getHospitalName, hosname);
        List<Hospital> hospitals = baseMapper.selectList(queryWrapper);
        return hospitals;
    }

}
